﻿@page "/settings"
@using System.Threading
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Identity;
@using BlazorBlogs.Data;
@using BlazorBlogs.Data.Models;
@using System.Net.Http
@inject UserManager<ApplicationUser> _UserManager
@inject RoleManager<IdentityRole> _RoleManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject IConfiguration _configuration
@inject IToastService toastService
@inject EmailService _EmailService
@inject GeneralSettingsService _GeneralSettingsService
@inject IHttpContextAccessor httpContextAccessor
@inject DisqusState DisqusState
@inject HttpClient Http
@inject NavigationManager UriHelper
@inherits OwningComponentBase

<h1>Settings</h1>
<!-- AuthorizeView allows us to only show sections of the page -->
<!-- based on the security on the current user -->
<AuthorizeView>
    <!-- Show this section if the user is logged in -->
    <Authorized>
        @if (@context.User.IsInRole(ADMINISTRATION_ROLE))
        {
            <table class="table">
                <tbody>
                    <tr>
                        <td>Application Version: <b>@objGeneralSettings.VersionNumber</b></td>
                        <td>
                            <RadzenUpload ChooseText="Upload Upgrade Package"
                                          Multiple="false"
                                          Accept="application/x-zip-compressed"
                                          Url=@($"api/upload/upgrade?FileTitle=BlazorBlogsUpgrade.zip")
                                          Progress="@((args) => OnProgress(args))" />
                        </td>
                    </tr>
                    <tr>
                        <td>Application Name</td>
                        <td>
                            <input class="form-control" type="text"
                                   @bind="objGeneralSettings.ApplicationName" />
                        </td>
                    </tr>
                    <tr>
                        <td>Application Logo</td>
                        <td>
                            <img src="@objGeneralSettings.ApplicationLogo" />
                            <button type="button" class="btn btn-link" @onclick="SelectLogo">[Select]</button>
                        </td>
                    </tr>
                    <tr>
                        <td>Application Header</td>
                        <td>
                            @if (!RichTextEditorMode)
                            {
                                <textarea class="form-control" @bind="@objGeneralSettings.ApplicationHeader" rows="5" />
                            }
                            <div style="@((!RichTextEditorMode) ? "display: none;":"")">
                                <BlazoredTextEditor @ref="@QuillHtml">
                                    <ToolbarContent>
                                        <select class="ql-header">
                                            <option selected=""></option>
                                            <option value="1"></option>
                                            <option value="2"></option>
                                            <option value="3"></option>
                                            <option value="4"></option>
                                            <option value="5"></option>
                                        </select>
                                        <span class="ql-formats">
                                            <button class="ql-bold"></button>
                                            <button class="ql-italic"></button>
                                            <button class="ql-underline"></button>
                                            <button class="ql-strike"></button>
                                        </span>
                                        <span class="ql-formats">
                                            <select class="ql-color"></select>
                                            <select class="ql-background"></select>
                                        </span>
                                        <span class="ql-formats">
                                            <button class="ql-list" value="ordered"></button>
                                            <button class="ql-list" value="bullet"></button>
                                        </span>
                                        <span class="ql-formats">
                                            <button class="ql-link"></button>
                                            <button class="btn btn-link" id="custom-button"
                                                    @onclick="InsertApplicationHeaderImageClick">
                                                <img src="imageIcon.png" style="border:hidden" />
                                            </button>
                                        </span>
                                    </ToolbarContent>
                                    <EditorContent>
                                        &nbsp;
                                    </EditorContent>
                                </BlazoredTextEditor>
                            </div>
                            @if (!RichTextEditorMode)
                            {
                                <button type="button" class="btn btn-link" @onclick="RichTextEditor"><h6>[Rich Text Editor]</h6></button>
                            }
                            else
                            {
                                <button type="button" class="btn btn-link" @onclick="RawHTMLEditor"><h6>[Raw HTML Editor]</h6></button>
                            }
                        </td>
                    </tr>
                    <tr>
                        <td>Allow Registration</td>
                        <td>
                            <select class="form-control"
                                    @bind="@AllowRegistration">
                                @foreach (var option in OptionsTrueFalse)
                                {
                                    <option value="@option">
                                        @option
                                    </option>
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Verified Registration</td>
                        <td>
                            <select class="form-control"
                                    @bind="@VerifiedRegistration">
                                @foreach (var option in OptionsTrueFalse)
                                {
                                    <option value="@option">
                                        @option
                                    </option>
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>SMTP Server</td>
                        <td>
                            <input class="form-control" type="text"
                                   @bind="objGeneralSettings.SMTPServer" />
                        </td>
                    </tr>
                    <tr>
                        <td>SMTP Authentication</td>
                        <td>
                            <select class="form-control"
                                    @bind="@SMTPAuthentication">
                                @foreach (var option in OptionsSMTP)
                                {
                                    <option value="@option">
                                        @option
                                    </option>
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>SMTP Secure</td>
                        <td>
                            <select class="form-control"
                                    @bind="@SMTPSecure">
                                @foreach (var option in OptionsTrueFalse)
                                {
                                    <option value="@option">
                                        @option
                                    </option>
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>SMTP User Name</td>
                        <td>
                            <input class="form-control" type="text"
                                   @bind="objGeneralSettings.SMTPUserName" />
                        </td>
                    </tr>
                    <tr>
                        <td>SMTP Password</td>
                        <td>
                            <input class="form-control" type="text"
                                   @bind="objGeneralSettings.SMTPPassword" />
                        </td>
                    </tr>
                    <tr>
                        <td>SMTP From Email</td>
                        <td>
                            <input class="form-control" type="text"
                                   @bind="objGeneralSettings.SMTPFromEmail" />
                        </td>
                    </tr>
                    <tr>
                        <td>Enable Disqus Comments</td>
                        <td>
                            <select class="form-control"
                                    @bind="@DisqusEnabled">
                                @foreach (var option in OptionsTrueFalse)
                                {
                                    <option value="@option">
                                        @option
                                    </option>
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Disqus ShortName</td>
                        <td>
                            <input class="form-control" type="text"
                                   @bind="objGeneralSettings.DisqusShortName" />
                        </td>
                    </tr>
                    <tr>
                        <td>Google Tracking ID</td>
                        <td>
                            <input class="form-control" type="text"
                                   @bind="objGeneralSettings.GoogleTrackingID" />
                        </td>
                    </tr>
                </tbody>
            </table>
            <br />
            <button class="btn btn-primary" @onclick="Save">Save</button>
            <button class="btn btn-success" @onclick="SendTestEmail">Send Test Email</button>
            <br /><br />
            <FileSelector @ref="FileManagerControl"
                         ImageSelected="InsertImage" />
            <FileSelector @ref="FileManagerApplicationHeaderControl"
                         ImageSelected="InsertApplicationHeaderImage" />

            @if (ShowProgressBarPopup)
            {
                <div class="modal" tabindex="-1" style="display:block" role="dialog">
                    <div class="modal-dialog modal-sm">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">Upgrade Status</h4>
                            </div>
                            <div align="center">
                                @if (!Upgrading)
                                {
                                    <RadzenProgressBar Value="@progress"
                                                       Unit="@info"
                                                       Visible="@(progress > 0)"
                                                       Style="margin-bottom: 20px" />
                                }
                                else
                                {
                                    @if (!ReadyToContinue)
                                    {
                                        <h4>Processing...</h4>
                                        <RadzenProgressBar Value="100" ShowValue="false" Mode="ProgressBarMode.Indeterminate" Style="margin-bottom: 20px" />
                                    }
                                    else
                                    {
                                        <RadzenLink Path="api/RestartApp/ShutdownSite" Text="Click here to Restart Site and Continue" target="_self" />
                                    }
                                }
                            </div>
                        </div>
                    </div>
                </div>
            }
        }
    </Authorized>
    <!-- Show this section if the user is not logged in -->
    <NotAuthorized>
        <p>You're not signed in.</p>
    </NotAuthorized>
</AuthorizeView>

@code {
    // AuthenticationState is available as a CascadingParameter
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    public System.Security.Claims.ClaimsPrincipal CurrentUser;
    string ADMINISTRATION_ROLE = "Administrators";

    GeneralSettings objGeneralSettings = new GeneralSettings();
    private FileSelector FileManagerControl;
    private FileSelector FileManagerApplicationHeaderControl;

    private bool ReadyToContinue = false;
    private bool Upgrading = false;
    private bool ShowProgressBarPopup = false;
    private int progress;
    private string info;

    BlazoredTextEditor QuillHtml;
    bool RichTextEditorMode = true;

    List<string> OptionsTrueFalse = new List<string>() { "True", "False" };
    List<string> OptionsSMTP = new List<string>() { "Anonymous", "Basic", "NTLM" };
    string AllowRegistration = "";
    string VerifiedRegistration = "";
    string SMTPSecure = "";
    string SMTPAuthentication = "";
    string DisqusEnabled = "";

    protected override async Task OnInitializedAsync()
    {
        // Get the current user
        CurrentUser = (await authenticationStateTask).User;

        _GeneralSettingsService = (GeneralSettingsService)ScopedServices.GetService(typeof(GeneralSettingsService));
        _EmailService = (EmailService)ScopedServices.GetService(typeof(EmailService));

        await LoadGeneralSettingsAsync();
        DisqusState.SetDisplayDisqus(false);
    }

    protected override async Task
        OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var GeneralSettings = await _GeneralSettingsService.GetGeneralSettingsAsync();
            await this.QuillHtml.LoadHTMLContent(GeneralSettings.ApplicationHeader);
        }
    }

    protected async Task LoadGeneralSettingsAsync()
    {
        objGeneralSettings = await _GeneralSettingsService.GetGeneralSettingsAsync();
        AllowRegistration = objGeneralSettings.AllowRegistration.ToString();
        VerifiedRegistration = objGeneralSettings.VerifiedRegistration.ToString();
        SMTPSecure = objGeneralSettings.SMTPSecure.ToString();
        DisqusEnabled = objGeneralSettings.DisqusEnabled.ToString();

        switch (objGeneralSettings.SMTPAuthendication.Trim())
        {
            case "":
            case "0":
                SMTPAuthentication = "Anonymous";
                break;
            case "1":
                SMTPAuthentication = "Basic";
                break;
            case "2":
                SMTPAuthentication = "NTLM";
                break;
        }
    }

    void SelectLogo()
    {
        FileManagerControl.SetShowFileManager(true);
    }

    void InsertImage(string paramImageURL)
    {
        objGeneralSettings.ApplicationLogo = paramImageURL;

        FileManagerControl.SetShowFileManager(false);
    }

    async Task InsertApplicationHeaderImage(string paramImageURL)
    {
        await this.QuillHtml.InsertImage(paramImageURL);

        FileManagerApplicationHeaderControl.SetShowFileManager(false);
    }

    private void InsertApplicationHeaderImageClick()
    {
        FileManagerApplicationHeaderControl.SetShowFileManager(true);
    }

    private async Task RichTextEditor()
    {
        RichTextEditorMode = true;
        await this.QuillHtml.LoadHTMLContent(objGeneralSettings.ApplicationHeader);
    }

    private async Task RawHTMLEditor()
    {
        RichTextEditorMode = false;
        objGeneralSettings.ApplicationHeader =
            await this.QuillHtml.GetHTML();
    }

    public async Task Save()
    {
        try
        {
            await SaveSettings();
            toastService.ShowSuccess("", "Saved!");
        }
        catch (Exception ex)
        {
            toastService.ShowSuccess("Error", ex.GetBaseException().Message);
        }
    }

    public async Task SaveSettings()
    {
        var AllowRegistrationResult = _GeneralSettingsService.UpdateAllowRegistrationAsync(Convert.ToBoolean(AllowRegistration));
        var VerifiedRegistrationResult = _GeneralSettingsService.UpdateVerifiedRegistrationAsync(Convert.ToBoolean(VerifiedRegistration));
        var SMTPSecureResult = _GeneralSettingsService.UpdateSMTPSecureAsync(Convert.ToBoolean(SMTPSecure));

        var UpdateApplicationNameResult = _GeneralSettingsService.UpdateApplicationNameAsync(objGeneralSettings.ApplicationName);
        var UpdateApplicationLogoResult = _GeneralSettingsService.UpdateApplicationLogoAsync(objGeneralSettings.ApplicationLogo);
        var UpdateSMTPServerResult = _GeneralSettingsService.UpdateSMTPServerAsync(objGeneralSettings.SMTPServer);
        var UpdateSMTPUserNameResult = _GeneralSettingsService.UpdateSMTPUserNameAsync(objGeneralSettings.SMTPUserName);
        var UpdateSMTPPasswordResult = _GeneralSettingsService.UpdateSMTPPasswordAsync(objGeneralSettings.SMTPPassword);
        var UpdateSMTPFromEmailResult = _GeneralSettingsService.UpdateSMTPFromEmailAsync(objGeneralSettings.SMTPFromEmail);

        var UpdateDisqusEnabledResult = _GeneralSettingsService.UpdateDisqusEnabledAsync(Convert.ToBoolean(DisqusEnabled));
        var UpdateDisqusShortNameResult = _GeneralSettingsService.UpdateDisqusShortNameAsync(objGeneralSettings.DisqusShortName);

        var UpdateGoogleTrackingIDResult = _GeneralSettingsService.UpdateGoogleTrackingIDAsync(objGeneralSettings.GoogleTrackingID);

        if (RichTextEditorMode)
        {
            objGeneralSettings.ApplicationHeader =
                await this.QuillHtml.GetHTML();
        }

        // If ApplicationHeader is essentially blank - - clear it
        if (objGeneralSettings.ApplicationHeader == @"<p><br></p>")
        {
            objGeneralSettings.ApplicationHeader = "";
        }

        var UpdateApplicationHeaderResult =
            _GeneralSettingsService.UpdateApplicationHeaderAsync(objGeneralSettings.ApplicationHeader);

        switch (SMTPAuthentication)
        {
            case "Anonymous":
                objGeneralSettings.SMTPAuthendication = "0";
                break;
            case "Basic":
                objGeneralSettings.SMTPAuthendication = "1";
                break;
            case "NTLM":
                objGeneralSettings.SMTPAuthendication = "2";
                break;
        }

        var UpdateSMTPAuthendicationResult =
            _GeneralSettingsService.UpdateSMTPAuthenticationAsync(objGeneralSettings.SMTPAuthendication);

        objGeneralSettings = await _GeneralSettingsService.GetGeneralSettingsAsync();
    }

    // Upload File

    private async Task OnProgress(UploadProgressArgs args)
    {
        ShowProgressBarPopup = true;
        this.info = $"{args.Loaded} of {args.Total} bytes.";
        this.progress = args.Progress;

        StateHasChanged();

        if (args.Loaded == args.Total)
        {
            Upgrading = true;
            StateHasChanged();

            await Task.Delay(5000);
            ReadyToContinue = true;
            StateHasChanged();
        }
    }

    public async Task SendTestEmail()
    {
        try
        {
            await SaveSettings();

            // Send Test Email
            string strError = await _EmailService.SendMailAsync(
                 false,
                 objGeneralSettings.SMTPFromEmail,
                 "Blazor-Blogs Administrator",
                 "", "",
                 objGeneralSettings.SMTPFromEmail,
                 "Blazor-Blogs SMTP Test Email",
                 $"This is a Blazor-Blogs SMTP Test Email from: { httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host}{httpContextAccessor.HttpContext.Request.PathBase}");

            if (strError == "")
            {
                toastService.ShowSuccess("", "Test Email Sent");
            }
            else
            {
                toastService.ShowError("", strError);
            }
        }
        catch (Exception ex)
        {
            toastService.ShowError("", ex.GetBaseException().Message);
        }
    }
}